package com.jash.encryption;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 */
public class Base64Fragment extends Fragment implements View.OnClickListener {


    private TextInputLayout src;
    private TextInputLayout rlt;

    public Base64Fragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_base64, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        src = ((TextInputLayout) view.findViewById(R.id.base64_src));
        rlt = ((TextInputLayout) view.findViewById(R.id.base64_rlt));
        view.findViewById(R.id.base64_encode).setOnClickListener(this);
        view.findViewById(R.id.base64_decode).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.base64_encode:
                rlt.setErrorEnabled(false);
                String src_str = src.getEditText().getText().toString();
                if (TextUtils.isEmpty(src_str)) {
                    src.setError("编码时，原文不可为空");
                    src.setErrorEnabled(true);
                } else {
                    src.setErrorEnabled(false);
                    String s = Base64.encodeToString(src_str.getBytes(), Base64.NO_WRAP);
                    rlt.getEditText().setText(s);
                }
                break;
            case R.id.base64_decode:
                src.setErrorEnabled(false);
                String rlt_src = rlt.getEditText().getText().toString();
                if (TextUtils.isEmpty(rlt_src)) {
                    rlt.setError("解码时，编码不可为空");
                    rlt.setErrorEnabled(true);
                } else {
                    rlt.setErrorEnabled(false);
                    byte[] decode = Base64.decode(rlt_src, Base64.NO_WRAP);
                    src.getEditText().setText(new String(decode));
                }
                break;
        }
    }
}
